import {Form, Input, Select, Upload, Button, message} from "antd"
import { UploadOutlined } from '@ant-design/icons'
import Layout from "../core/Layout"
import { useState } from "react"
import axios from 'axios'
import {API} from '../../config'
import { isAuth } from "../../helpers/auth"
import { useHistory } from "react-router-dom"
import useGetCategories from '../../helpers/categories'
function AddProduct () {
    
    
    const [file,setFile] = useState()
    const categories = useGetCategories()
    const {user,token} = isAuth()
    const [form] = Form.useForm()
    const history = useHistory()

    const props = {
        beforeUpload:(file)=>{
            setFile(file)
            return false
        }
    }
   
    const handleOnFinish = (value) => {
        const formdata = new FormData()
        for (let key in value) {
            formdata.append(key,value[key])
        }
        formdata.append("photo",file)
        axios.post(`${API}/product/create/${user._id}`,formdata,{headers:{Authorization:`Bearer ${token}`}})
        .then(response => {
            message.success('创建成功')
            form.resetFields()
            history.push('/admin/dashboard')
        })
    }
    return (
       <Layout title="添加商品">
           <Form initialValues={{"category":"-1"}} onFinish={handleOnFinish} form={form}>
               <Form.Item>
                <Upload {...props}>
                    <Button icon={<UploadOutlined />}>上传商品封面</Button>
                </Upload>
               </Form.Item>
               <Form.Item name="name" label="商品名称">
                   <Input />
               </Form.Item>
               <Form.Item name="description" label="商品描述">
                   <Input />
               </Form.Item>
               <Form.Item name="price" label="商品价格">
                   <Input />
               </Form.Item>
               <Form.Item name="category" label="商品分类">
                   <Select >
                       <Select.Option value="-1">请选择分类</Select.Option>
                       {categories.map(item => (
                        <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>
                       ))}
                       
                   </Select>
               </Form.Item>
               <Form.Item name="shipping" label="是否需要运输">
                   <Select>
                       <Select.Option value={1}>是</Select.Option>
                       <Select.Option value={0}>否</Select.Option>
                   </Select>
               </Form.Item>
               <Form.Item name="quantity" label="商品数量">
                   <Input />
               </Form.Item>
               <Form.Item>
                   <Button type="primary" htmlType="submit">添加商品</Button>
               </Form.Item>
           </Form>
       </Layout>
    )
}
export default AddProduct